home *** CD-ROM | disk | FTP | other *** search
- Path: quasar.engr.sgi.com!davea
- From: davea@quasar.engr.sgi.com (David B.Anderson)
- Newsgroups: comp.lang.c
- Subject: Re: Nested Structures in C - A Question
- Date: 28 Jan 1996 19:17:42 GMT
- Organization: Silicon Graphics, Inc., Mountain View, CA
- Message-ID: <4egi4m$4ik@fido.asd.sgi.com>
- References: <36400002@peg>
- NNTP-Posting-Host: quasar.engr.sgi.com
-
- In article <36400002@peg>, <tmccoy@peg.apc.org> wrote:
- >A Question on Nested Structures in C
- >struct outer {
- > int var1;
- > int var2;
- > int var3;
- >};
- >
- >Apparently the compiler will NOT allocate any storage when
- >I do this because, according to Kernighan and Ritchie (2nd
- >Ed), "a structure declaration that is not followed by a
- >list of variables reserves no storage; it merely describes
- >a template or the shape of a structure" (Page 128).
- >
-
- >struct outer {
- > int var1;
- > int var2;
- > int var3;
- > struct inner {
- > int nested1;
- > int nested2;
- > };
- >};
-
- >and I should be able to define an instance of my structure
- >by doing:
- >
- >struct outer instance;
- >
- >and refer to the first member of my inner structure by doing:
- >
- >instance.inner.nested1
- >
- >Yet, C won't let me do this!! It insists that I define my
- >nested structure as follows:
- [long discussion about the above deleted to save space]
-
- The declaration
- struct outer {
- int var1;
- int var2;
- int var3;
- struct inner {
- int nested1;
- int nested2;
- };
- };
- declares a struct outer with 3 members, var1, var2, var3.
- Because, in ISO C, struct outer { ...} is not a scope,
- and because there is no 'instance of inner which is a member
- of outer'
- this is identical to the following pair of declarations:
-
-
- struct outer {
- int var1;
- int var2;
- int var3;
- /* no instance of 'inner' */
- };
- /* no scope, so 'inner' is really a struct just as visible as 'outer'. */
- struct inner {
- int nested1;
- int nested2;
- };
-
- (Identical aside from the question of when 'struct inner' becomes visisble
- during compilation of the declarations).
-
- If you want to refer to an 'inner' in 'outer' you must declare such.
- Here is a clearer (for C) way to do this, one which reflects the
- true declaration scope and creates an 'inner' member in 'outer'.
-
- struct inner {
- int nested1;
- int nested2;
- };
- struct outer {
- int var1;
- int var2;
- int var3;
- struct inner var4; /* here we have an 'inner' member */
- };
-
- struct outer instance2;
- instance2.var4.nested1 = 0;
-
- Note that in C++, things are quite different: each struct/class *is*
- a scope, so the above would not be a correct analysis for C++.
-
- Hope this makes sense.
- [ David B. Anderson (415)933-4263 davea@sgi.com ]
- [ Suddenly to me that no verb in this sentence. -m.toy]
-